package com.glela.api.sms.yunxin;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.glela.api.sms.util.CheckSumBuilder;
import com.glela.api.sms.yunxin.vo.URLParameter;

/**
 * 
 * @author houmf
 * @version 创建时间：2016年6月22日 下午3:55:17
 * @name 发送短信
 */
public class SendMSM {
	/*public static void main(String[] args) throws Exception {
		List<URLParameter> list = new ArrayList<URLParameter>();
		list.add(new URLParameter("mobile", "15921002625"));
		list.add(new URLParameter("code", "7365"));
		System.out.println(send("verifyCode", list));
	}*/

	private static Map<String, String> getURLMap() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("sendCode", "https://api.netease.im/sms/sendcode.action");// 发验证码
		map.put("verifyCode", "https://api.netease.im/sms/verifycode.action");// 校验验证码
		map.put("sendTemplate", "https://api.netease.im/sms/sendtemplate.action"); // 发送模板短信

		return map;
	}

	/**
	 * 发送验证
	 * 
	 * @param urlKey
	 *            sendCode 发验证码,verifyCode 校验验证码,sendTemplate 发送模板短信
	 * @param list 参数集合
	 * @return
	 */
	public static String send(String urlKey, List<URLParameter> list) {
		String json = "";
		Map<String, String> map = getURLMap();
		String url = map.get(urlKey);
		if (url == null || "".equals(url)) {
			return json ;
		}
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);

		String appKey = "58b0ba4936e88c8610ffe1e22070a789";
		String appSecret = "7d4450d9af48";
		String nonce = "bububa2016";// nonce随机数
		String curTime = String.valueOf((new Date()).getTime() / 1000L);// time
		String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);// 参考计算CheckSum的java代码

		// 设置请求的header
		httpPost.addHeader("AppKey", appKey);
		httpPost.addHeader("Nonce", nonce);
		httpPost.addHeader("CurTime", curTime);
		httpPost.addHeader("CheckSum", checkSum);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

		// 设置请求的的参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		// 参数 jsonArray形式
		for (URLParameter parameter : list) {
			nvps.add(parameter.getURLParameter());
		}
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			// 执行请求
			HttpResponse response = httpClient.execute(httpPost);

			// 打印执行结果
			json = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json;

	}
}
